package com.fingard.dsp.bank.directbank.citic42;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;

/**
 * @author dicke
 * @date 2018/3/14 14:54
 */
public class CITIC42Base extends DirectBase implements ITcpClient {

    protected void writeCommonHeader(StringBuilder req_message, CITIC42Header p_bankHeader) throws Exception {
        //req_message.append(p_bankHeader.messageLength);
        req_message.append(p_bankHeader.messageFixedHeader);
        req_message.append(p_bankHeader.messageSerialno).append("|");
        req_message.append(p_bankHeader.messageType).append("|");
    }

    protected String getCharset(){
        return getBankConfig().getCharset("GBK");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        String tmpCharset = getCharset();
        /*byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);
        String tmpHead = "0" + String.format("%-29d", tmpBytesBody.length);
        byte[] tmpBytesHead = tmpHead.getBytes(tmpCharset);

        byte[] tmpBytesSend = new byte[tmpBytesHead.length + tmpBytesBody.length];
        System.arraycopy(tmpBytesHead, 0, tmpBytesSend, 0, tmpBytesHead.length);
        System.arraycopy(tmpBytesBody, 0, tmpBytesSend, tmpBytesHead.length, tmpBytesBody.length);

        WriteBankLogStep2(tmpHead + p_reqStr);*/
        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr.getBytes(tmpCharset));
        if (StringHelper.isNullOrEmpty(tmpReceiver.connState)) {
            String tmpBkStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(tmpBkStr);
        }
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.isCompleted) {
            retStr[1] = new String(tmpReceiver.recBytes, tmpReceiver.contentStartIndex, tmpReceiver.contentLength, tmpCharset);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
            WriteBankLogLn(retStr[1]);
        }
        return retStr;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 29) {
                String tmpHead = new String(p_receiver.recBytes, 0, 8, getCharset());
                p_receiver.contentLength = Integer.parseInt(tmpHead);
                p_receiver.contentStartIndex = 8;
            }
        }
    }
}
